import { useEffect, useState } from 'react';
import { Table, Button, Tag, Card, Input, Modal, Form, message, Space, Select, DatePicker } from 'antd';
import { PlusOutlined, EditOutlined, CheckOutlined } from '@ant-design/icons';
import { getWines, createWine, updateWine, takeWine } from '../api/wines';
import { getUsers } from '../api/users';
import dayjs from 'dayjs';

const Wines = () => {
  const [wines, setWines] = useState([]);
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [editingWine, setEditingWine] = useState(null);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
  const [form] = Form.useForm();

  useEffect(() => {
    fetchWines();
    fetchUsers();
  }, [pagination.current, pagination.pageSize, status]);

  const fetchWines = async () => {
    setLoading(true);
    try {
      const params = { page: pagination.current, limit: pagination.pageSize };
      if (status) params.status = status;

      const response = await getWines(params);
      if (response.success) {
        setWines(response.data.wines);
        setPagination(prev => ({ ...prev, total: response.data.pagination.total }));
      }
    } catch (error) {
      console.error('Fetch wines error:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchUsers = async () => {
    try {
      const response = await getUsers({ limit: 1000 });
      if (response.success) {
        setUsers(response.data.users.filter(u => u.role === 'customer'));
      }
    } catch (error) {
      console.error('Fetch users error:', error);
    }
  };

  const openModal = (wine = null) => {
    setEditingWine(wine);
    if (wine) {
      form.setFieldsValue({ ...wine, storageDate: dayjs(wine.storageDate) });
    } else {
      form.resetFields();
    }
    setModalVisible(true);
  };

  const handleSubmit = async (values) => {
    try {
      const data = { ...values, storageDate: values.storageDate.format('YYYY-MM-DD') };
      if (editingWine) {
        await updateWine(editingWine.id, data);
        message.success('更新成功');
      } else {
        await createWine(data);
        message.success('寄存成功');
      }
      setModalVisible(false);
      fetchWines();
    } catch (error) {
      console.error('Submit error:', error);
    }
  };

  const handleTakeWine = async (id) => {
    try {
      await takeWine(id);
      message.success('取酒成功');
      fetchWines();
    } catch (error) {
      console.error('Take wine error:', error);
    }
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
    {
      title: '用户',
      dataIndex: ['user', 'name'],
      key: 'userName',
      render: (_, record) => `${record.user.name} (${record.user.phone})`
    },
    { title: '酒名', dataIndex: 'wineName', key: 'wineName' },
    { title: '类型', dataIndex: 'wineType', key: 'wineType' },
    {
      title: '数量',
      key: 'quantity',
      render: (_, record) => `${record.quantity} ${record.unit}`
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'stored' ? 'green' : 'default'}>
          {status === 'stored' ? '在库' : '已取出'}
        </Tag>
      )
    },
    {
      title: '寄存日期',
      dataIndex: 'storageDate',
      key: 'storageDate',
      render: (date) => dayjs(date).format('YYYY-MM-DD')
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => openModal(record)}
          >
            编辑
          </Button>
          {record.status === 'stored' && (
            <Button
              type="link"
              size="small"
              icon={<CheckOutlined />}
              onClick={() => handleTakeWine(record.id)}
            >
              取酒
            </Button>
          )}
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card
        title="寄存酒管理"
        extra={
          <Space>
            <Select
              style={{ width: 120 }}
              placeholder="状态筛选"
              allowClear
              onChange={setStatus}
              options={[
                { value: 'stored', label: '在库' },
                { value: 'taken', label: '已取出' }
              ]}
            />
            <Button type="primary" icon={<PlusOutlined />} onClick={() => openModal()}>
              寄存酒
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={wines}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={(newPagination) => setPagination(prev => ({
            ...prev,
            current: newPagination.current,
            pageSize: newPagination.pageSize
          }))}
        />
      </Card>

      <Modal
        title={editingWine ? '编辑寄存酒' : '寄存酒'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form form={form} onFinish={handleSubmit} layout="vertical">
          <Form.Item
            name="userId"
            label="用户"
            rules={[{ required: true, message: '请选择用户' }]}
          >
            <Select
              showSearch
              placeholder="选择用户"
              filterOption={(input, option) =>
                option.label.toLowerCase().includes(input.toLowerCase())
              }
              options={users.map(u => ({ value: u.id, label: `${u.name} (${u.phone})` }))}
              disabled={!!editingWine}
            />
          </Form.Item>
          <Form.Item
            name="wineName"
            label="酒名"
            rules={[{ required: true, message: '请输入酒名' }]}
          >
            <Input placeholder="例如：茅台" />
          </Form.Item>
          <Form.Item
            name="wineType"
            label="酒类型"
            rules={[{ required: true, message: '请输入酒类型' }]}
          >
            <Input placeholder="例如：白酒" />
          </Form.Item>
          <Form.Item
            name="quantity"
            label="数量"
            rules={[{ required: true, message: '请输入数量' }]}
          >
            <Input type="number" placeholder="数量" />
          </Form.Item>
          <Form.Item name="unit" label="单位" initialValue="瓶">
            <Input placeholder="单位" />
          </Form.Item>
          <Form.Item
            name="storageDate"
            label="寄存日期"
            rules={[{ required: true, message: '请选择日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item name="notes" label="备注">
            <Input.TextArea rows={3} placeholder="选填" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                确认
              </Button>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Wines;
